<!--
 * @description:
 * @fileName: index
 * @author: luhuixu
 * @date: 2023/5/29-12:17
 * @version: V1.0.0
-->
<template>
  <span :endTime="endTime" :endText="endText">
    <slot>{{ content }}</slot>
  </span>
</template>

<script>
export default {
  name: 'CountDown',
  props: { // 接收父组件的数据
    // 时间戳格式
    endTime: {
      type: Number,
      default: 0
    },
    // 结束文本
    endText: {
      type: String,
      default: '报名已截止'
    },
    // 是否显示时间前缀
    showPrefix: {
      type: Boolean,
      default: false
    },
    // 前缀
    prefixText: {
      type: String,
      default: '学习中：'
    }
  },
  data() {
    return {
      content: '',
      timer: null
    }
  },
  watch: { // 监听时间的变化
    endTime() {
      this.countdowm(this.endTime)
    }
  },
  mounted() {
    this.countdowm(this.endTime)
  },
  beforeDestroy() {
    clearInterval(this.timer)
    this.timer = null
  },
  methods: {
    countdowm(timestamp) {
      const self = this
      if (self.timer) {
        clearInterval(self.timer)
      }
      self.timer = setInterval(function() {
        const nowTime = new Date()
        const endTime = new Date(timestamp).getTime()
        const t = endTime - nowTime.getTime()
        if (t > 0) {
          const day = Math.floor(t / 86400000)
          let hour = Math.floor((t / 3600000) % 24)
          let min = Math.floor((t / 60000) % 60)
          let sec = Math.floor((t / 1000) % 60)
          hour = hour < 10 ? '0' + hour : hour
          min = min < 10 ? '0' + min : min
          sec = sec < 10 ? '0' + sec : sec
          let format = ''
          if (day > 0) {
            format = `${day}天${hour}小时${min}分${sec}秒`
          }
          if (day <= 0 && hour > 0) {
            format = `${hour}小时${min}分${sec}秒`
          }
          if (day <= 0 && hour <= 0) {
            format = `${min}分${sec}秒`
          }
          self.content = self.showPrefix ? self.prefixText + format : format
          self.$emit('change', t)
        } else {
          clearInterval(self.timer)
          self.timer = null
          self.content = self.endText
          self.$emit('end')
        }
      }, 1000)
    }
  }
}
</script>

